package lock;

import java.util.concurrent.Semaphore;

/**
 * @author tongchen
 * @create 2023-08-11 21:21
 */
public class SemaphoreTest {
    public static void main(String[] args) {
        //创建信号量
        Semaphore semaphore = new Semaphore(5);
        //创建任务
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName() + "准备好了");
                try {
                    Thread.sleep(2000);
                    System.out.println(Thread.currentThread().getName() + "在执行任务");
                    semaphore.release();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        };
        //创建线程并执行
        for(int i=0;i<10;++i){
            Thread thread = new Thread(runnable);
            thread.start();
        }
    }
}
